// 营业员分期消费控制器模块
// 
import {
    viewInit,
    showPromptDialog,
    hidePromptDialog,
    showLoadingDialog,
    hideLoadingDialog
} from '../views/spendingView.js';

import {
    getConfig
} from '../components/wxConfig.js';
var cw = require("../components/winLocation.js");
import {} from '../base/observer.js';
import {
    errorDialog
} from '../components/errorDialog.js';
import {
    Logout
} from '../components/logout.js';
var logoutObject;

var token, loginName, openid, loginType, mer_no, latitude, longitude, mer_id, lastPage;
var $money;
$(document).on("pageinit", "#spending_page", controllerInit);
var stringcode = "sdfdsf";

var oneErrorObject;
//var baseurl, wlprotocol, get_config_url;
// 控制器初始化
function controllerInit() {
    cw.checkBrowser();
    viewInit();
    initValue();
    saomaEvent();
    getWxScanQRCode();
    bindSubscribe();
    bindEvent();
    $("#fanhui").on("touchstart", function() {
        if (lastPage == "merchant") {
            location.href = "./merchantHome.html";
        } else {
            location.href = "./staffHome.html";
        }
    });
}

//  扫描动作
function saomaEvent() {
    $("#saoma").on("click", function() {
        // 到注释掉 getInstServlet(); 得到经纬度后调
        //        getInstServlet();
        if ($(this).hasClass("weui-btn_disabled")) {
            if (parseFloat($money.val()) >= 1000000) {
                oneErrorObject.showErroDialog("消费金额不能大于100万");
            } else if (parseFloat($money.val()) < 1) {
                oneErrorObject.showErroDialog("消费金额不能小于1元");
            } else {
                oneErrorObject.showErroDialog("请输入消费金额");
            }

            return;
        } else {
            showLoadingDialog();
            getWxScanQRCode();
        }

    });
}

// 请求消费接口
function getInstServlet() {
    var money = $money.val();
    var parameters = {
        token: token,
        loginName: loginName,
        openid: openid,
        loginType: loginType,
        latitude: latitude,
        longitude: longitude,
        serial_no: stringcode,
        tl_mer_no: mer_id,
        goods_amount: money

    };
    var saoma_URL = InstServlet_URL;
    if (lastPage == "merchant") {
        saoma_URL = MerInstServlet_URL;
    }
    $.post(saoma_URL, parameters, xfback);

}

// 消费扫码返回函数
function xfback(msg) {
    console.dir(msg);
    hideLoadingDialog();
    if (msg.login_response) {
        haslogin(msg);
    } else if (msg.lft_orderinfo_response && msg.lft_orderinfo_response.resp_code == "0000") {
        $money.val("");
        location.href = "./success.html?fromPage=" + lastPage + "&money=" + $money.val();
    } else if (msg.lft_orderinfo_response && msg.lft_orderinfo_response.resp_code == "0112") {
        showPromptDialog("进行消费的商户尚未签到，是否现在签到?");
    } else if (msg.lft_orderinfo_response && msg.lft_orderinfo_response.resp_code && msg.lft_orderinfo_response.resp_msg) {
        oneErrorObject.showErroDialog(msg.lft_orderinfo_response.resp_code + ":" + msg.lft_orderinfo_response.resp_msg);
    } else {
        oneErrorObject.showErroDialog("支付失败");
    }
}

// 再次签到
function signAgain() {
    $.post(
        SignServletUrl, {
            loginName: loginName,
            token: token,
            openid: openid,
            latitude: latitude,
            longitude: longitude,
            loginType: loginType,
            state: "1"
        },
        signAgainCallBack
    );
}

// 签到成功回调函数
function signAgainCallBack(saData) {
    console.dir(saData);
    if (saData.sign_response && saData.sign_response.resp_code == "0000") {
        hidePromptDialog();
        oneErrorObject.showErroDialog("签到成功");
    } else {
        hidePromptDialog();
        oneErrorObject.showErroDialog("签到失败");
    }
}
// 绑定事件
function bindEvent() {
    $("#open-again").on("touchend", signAgain)
}

// 初始化变量
function initValue() {
    getConfig(get_wxconfig_url, {
        "mapUrl": "/tltd/spending.html" + location.search
    }, ['getLocation', 'scanQRCode']);
    getSessionStorage();
    oneErrorObject = new errorDialog();
    cw.QueryString.Initial();
    lastPage = cw.QueryString.GetValue("lastPage");
    $money = $("#money");
    logoutObject = new Logout();
}

// 监听获取经纬度和扫码得到串码
function bindSubscribe() {
    $.subscribe("scanQRCodeLocation", function() {
        if (latitude == undefined || longitude == undefined) {
            console.log("扫码结束,等待经纬度");
        } else if (stringcode == undefined) {
            console.log("经纬度结束,等待扫码");
        } else {
            getInstServlet();
        }
    });
}


// 调微信扫描
function getWxScanQRCode() {
    wx.scanQRCode({
        needResult: 1,
        desc: 'scanQRCode desc',
        success: function(res) {
            // 扫码后获取结果参数:htpp://xxx.com/c/?6123，截取到url中的防伪码后，赋值给Input
            stringcode = res.resultStr.substr(-18);
            //            alert(stringcode);
            getLocation();
            //  var tempArray = url.split('?');
            //  var tempNum = tempArray[1];
            // $("#id_securityCode_input").val(tempNum);

        },
        fail: function() {
            oneErrorObject.showErroDialog("扫码失败,请确认是否授权微信调用摄像头权限");
        },
        cancel: function(res) {
            hideLoadingDialog();
        }
    });

}

// 配置成功获取经纬度
function getLocation() {

    wx.getLocation({
        type: "gcj02",
        success: function(res) {
            console.log("getLocation data");
            console.dir(res);
            latitude = res.latitude;
            longitude = res.longitude;
            //        alert("当前地理位置：经度 " + latitude + "纬度 " + longitude);
            $.publish("scanQRCodeLocation");
        },
        fail: function() {
            oneErrorObject.showErroDialog("获取地理位置失败,请确认是否打开地理位置定位功能并授权微信获得地理位置权限");
        },
        cancel: function(res) {
            alert('用户拒绝授权获取地理位置');
        }
    });

}

// 判断是否有效登入
function haslogin(msg) {
    if (msg.login_response) {
        oneErrorObject.showErroDialog("该账户已在别的地方登录,请重新登入");
        setTimeout(function() {
            location.href = LoginInit_URL;
        }, 3000);
    }
}


// 取本地存储essionStorage
function getSessionStorage() {
    token = sessionStorage.getItem("tltd_token");
    loginName = sessionStorage.getItem("tltd_loginName");
    openid = sessionStorage.getItem("tltd_openid");
    loginType = sessionStorage.getItem("tltd_loginType");
    mer_id = sessionStorage.getItem("mer_id");
    //    mer_no = sessionStorage.getItem("mer_no")
    console.log(token, loginName, openid, loginType);
}